package com.sky.web.app;

import cn.hutool.core.collection.CollUtil;
import com.sky.context.UserHolder;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.awt.print.Book;
import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Slf4j
public class AppAddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    // 查询购物车列表
    @GetMapping("/list")
    public Result findList() {
        log.info("查询购物车列表");
        //1 获取登录人id
        Long userId = UserHolder.get();
        //2 封装查询条件
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(userId);
        // 3 调用service查询
        List<AddressBook> list = addressBookService.findList(addressBook);
        // 4 返回结果
        return Result.success(list);
    }

    // 新增地址
    @PostMapping
    public Result save(@RequestBody AddressBook addressBook) {
        log.info("新增地址:{}", addressBook);
        //2 调用service保存
        addressBookService.save(addressBook);
        //3 返回结果
        return Result.success();
    }

    // 设置默认地址
    @PutMapping("/default")
    public Result setDefault(@RequestBody AddressBook addressBook) {
        log.info("设置默认地址:{}", addressBook);
        // 调用service
        addressBookService.setDefault(addressBook);
        return Result.success();
    }

    // 查询默认地址
    @GetMapping("/default")
    public Result getDefault() {
        log.info("查询默认地址");
        //1 获取登录人id
        Long userId = UserHolder.get();
        //2 封装查询条件
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(userId);
        addressBook.setIsDefault(1);
        // 3 调用service查询
        List<AddressBook> list = addressBookService.findList(addressBook);
        if (CollUtil.isNotEmpty(list)) {
            AddressBook ab = list.get(0);
            return Result.success(ab);
            //return Result.success(list.get(0));
        }else {

            return Result.error("没有默认地址");
        }
    }

    // 根据ID回显地址信息
    @GetMapping("/{id}")
    public Result getAddressById(@PathVariable Long id) {
        log.info("回显地址:{}", id);
        //1 调用service查询
        AddressBook addressBook = addressBookService.findById(id);
        //2 返回结果
        return Result.success(addressBook);
    }

    // 修改地址
    @PutMapping
    public Result update(@RequestBody AddressBook addressBook) {
        log.info("修改地址:{}", addressBook);
        //2 调用service修改
        addressBookService.update(addressBook);
        //3 返回结果
        return Result.success();
    }

    // 删除地址
    @DeleteMapping
    public Result delete(Long id) {
        log.info("删除地址:{}", id);
        //2 调用service删除
        addressBookService.delete(id);
        //3 返回结果
        return Result.success();
    }
}
